package cn.ztuo.bitrade.service;

import cn.ztuo.bitrade.constant.TransactionType;
import cn.ztuo.bitrade.dao.LoanMoneyDao;
import cn.ztuo.bitrade.dao.MemberDao;
import cn.ztuo.bitrade.dao.MemberTransactionDao;
import cn.ztuo.bitrade.dao.MemberWalletDao;
import cn.ztuo.bitrade.entity.*;
import cn.ztuo.bitrade.service.Base.BaseService;
import cn.ztuo.bitrade.util.BigDecimalUtils;
import cn.ztuo.bitrade.util.PredicateUtils;
import cn.ztuo.bitrade.vo.BorrowMoneyVO;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author: Xiazt
 * @date: 2020-04-27 14:05
 */
@Service
public class LoanMoneyService extends BaseService {

    @Autowired
    private LoanMoneyDao loanMoneyDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private MemberWalletDao memberWalletDao;

    @Autowired
    private MemberTransactionDao memberTransactionDao;

    @Autowired
    private CoinService coinService;

    @Transactional
    public LoanMoney saveOrUpdate(Long memberId, LoanMoney loanMoney, MemberWallet memberWallet) {
        if (loanMoney.getLoanAmount().compareTo(BigDecimal.ZERO) <= 0) throw new RuntimeException("数据异常！");
        Member member = memberDao.findOne(memberId);
        loanMoney.setJoinMember(member);
        loanMoney.setLoanCoin("USDT");
        LoanMoney result = loanMoneyDao.save(loanMoney);
        // 扣除余额
        memberWallet.setBalance(BigDecimalUtils.sub(memberWallet.getBalance(), loanMoney.getLoanAmount()));
        memberWalletDao.save(memberWallet);
        // 借出资产流水
        MemberTransaction loanTransaction = new MemberTransaction();
        loanTransaction.setMemberId(memberId);
        loanTransaction.setSymbol("USDT");
        loanTransaction.setCreateTime(new Date());
        loanTransaction.setAmount(loanMoney.getLoanAmount().negate());
        // 借贷流水
        loanTransaction.setType(TransactionType.LOAN_RECORD);
        memberTransactionDao.save(loanTransaction);
        return result;
    }

    public Page<LoanMoney> getLoanMoneyList(BorrowMoneyVO borrowMoneyVO) {
        ArrayList<BooleanExpression> booleanExpressions = new ArrayList<>();
        // 查询条件
        if (borrowMoneyVO.getPeriod() != null) {
            booleanExpressions.add(QLoanMoney.loanMoney.period.eq(borrowMoneyVO.getPeriod()));
        }
        if (borrowMoneyVO.getMemberId() != null) {
            booleanExpressions.add(QLoanMoney.loanMoney.joinMember.id.eq(borrowMoneyVO.getMemberId()));
        } else {
            booleanExpressions.add(QLoanMoney.loanMoney.status.ne(3));
        }
        if (borrowMoneyVO.getUsername() != null) {
            booleanExpressions.add(QBorrowMoney.borrowMoney.joinMember.username.eq(borrowMoneyVO.getUsername()));
        }
        if (borrowMoneyVO.getPhoneNumber() != null) {
            booleanExpressions.add(QBorrowMoney.borrowMoney.joinMember.mobilePhone.eq(borrowMoneyVO.getPhoneNumber()));
        }
        Predicate predicate = PredicateUtils.getPredicate(booleanExpressions);
        // 排序条件
        // 排序条件
        Sort sort;
        if ("DESC".equals(borrowMoneyVO.getSort())) {
            sort = new Sort(Sort.Direction.DESC, borrowMoneyVO.getSortField());
        } else {
            sort = new Sort(Sort.Direction.ASC, borrowMoneyVO.getSortField());
        }
        Pageable pageable = new PageRequest(borrowMoneyVO.getPageNum() - 1, borrowMoneyVO.getPageSize(), sort);
        Page<LoanMoney> all = loanMoneyDao.findAll(predicate, pageable);
        for (LoanMoney loanMoney : all) {
            loanMoney.getMember().setId(loanMoney.getJoinMember().getId());
            loanMoney.getMember().setUsername(loanMoney.getJoinMember().getUsername());
        }

        return all;
    }

    public LoanMoney findById(Long id) {
        return loanMoneyDao.findById(id);
    }

    @Transactional
    public LoanMoney cancellations(Long memberId, LoanMoney loanMoney) {
        // 退回借出金额
        if (loanMoney.getLoanAmount().compareTo(BigDecimal.ZERO) <= 0) throw new RuntimeException("数据异常！");
        Coin loanMoneyCoin = coinService.findByUnit("USDT");
        MemberWallet loanMoneyMemberWallet = memberWalletDao.findByCoinAndMemberId(loanMoneyCoin, memberId);
        loanMoneyMemberWallet.setBalance(BigDecimalUtils.add(loanMoneyMemberWallet.getBalance(), loanMoney.getLoanAmount()));
        memberWalletDao.save(loanMoneyMemberWallet);
        // 退回借出金额资产流水
        MemberTransaction loanTransaction = new MemberTransaction();
        loanTransaction.setMemberId(memberId);
        loanTransaction.setSymbol("USDT");
        loanTransaction.setCreateTime(new Date());
        loanTransaction.setAmount(loanMoney.getLoanAmount());
        // 借贷流水
        loanTransaction.setType(TransactionType.LOAN_RECORD);
        memberTransactionDao.save(loanTransaction);

        // 状态修改为已撤单
        loanMoney.setStatus(3);
        return loanMoneyDao.save(loanMoney);
    }
}
